<template>
  <div class="api-test-container">
    <h2>API测试工具</h2>
    <div class="test-controls">
      <el-button type="primary" @click="runTest">运行API测试</el-button>
      <el-button @click="clearLogs">清除日志</el-button>
    </div>
    <div class="test-results">
      <el-card v-if="logs.length > 0" class="logs-card">
        <template #header>
          <div class="card-header">
            <span>测试日志</span>
          </div>
        </template>
        <pre class="logs-content">{{ logs.join('\n') }}</pre>
      </el-card>
      <div v-else class="no-logs">
        暂无测试日志，请点击"运行API测试"按钮开始测试
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { testRegisterApi } from '@/api'
import { ElButton, ElCard } from 'element-plus'
import 'element-plus/dist/index.css'

const logs = ref([])

// 记录日志
function log(message) {
  logs.value.push(`[${new Date().toLocaleTimeString()}] ${message}`)
}

// 运行API测试
async function runTest() {
  logs.value = []
  log('开始运行API测试...')
  
  try {
    // 重写console.log，捕获测试过程中的输出
    const originalConsoleLog = console.log
    console.log = (...args) => {
      log(args.map(arg => typeof arg === 'object' ? JSON.stringify(arg) : arg).join(' '))
      originalConsoleLog.apply(console, args)
    }
    
    // 运行测试
    const result = await testRegisterApi()
    
    // 恢复console.log
    console.log = originalConsoleLog
    
    if (result.success) {
      log('✅ API测试成功！')
    } else {
      log(`❌ API测试失败: ${result.error}`)
    }
  } catch (error) {
    log(`❌ 测试过程中发生错误: ${error.message}`)
  }
}

// 清除日志
function clearLogs() {
  logs.value = []
}
</script>

<style scoped>
.api-test-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

h2 {
  margin-bottom: 20px;
  color: #303133;
}

.test-controls {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.test-results {
  min-height: 300px;
}

.logs-card {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logs-content {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  font-family: monospace;
  white-space: pre-wrap;
  word-break: break-all;
  max-height: 500px;
  overflow-y: auto;
  margin: 0;
}

.no-logs {
  text-align: center;
  padding: 40px;
  color: #909399;
  background-color: #f5f7fa;
  border-radius: 4px;
}
</style>